﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ExplorerService.Common.Logging
{
    /// <summary>
    /// Trace listener used to output logs to the system event logs for the service
    /// WORK IN PROGRESS!
    /// </summary>
    public abstract class ReflectedTraceListener : TextWriterTraceListener
    {
        public override void Write(string message)
        {
            base.Write(ReflectedLocation() + message);
        }

        public override void WriteLine(string message)
        {
            var location = ReflectedLocation();
            Console.WriteLine(location + message);
            base.WriteLine(ReflectedLocation() + message);
        }
        private static string ReflectedLocation()
        {
            var locationBuilder = new StringBuilder();
            var stackTrace = new StackTrace();
            StackFrame stackFrame;
            MethodBase stackFrameMethod;
            var frameCount = 0;
            string typeName;
            do
            {
                frameCount++;
                stackFrame = stackTrace.GetFrame(frameCount);
                stackFrameMethod = stackFrame.GetMethod();
                typeName = stackFrameMethod.ReflectedType.FullName;
            } while (typeName.StartsWith("System") || typeName.EndsWith("ReflectedTraceListener"));


            locationBuilder.Append(DateTime.Now.ToString());
            locationBuilder.Append(": ");
            locationBuilder.Append(typeName);
            locationBuilder.Append(".");
            locationBuilder.Append(stackFrameMethod.Name);
            locationBuilder.Append(" - ");
            return locationBuilder.ToString();
        }
    }
}
